<template>
  <div class="personInformation">
    <el-container>
      <el-aside width="200px" style="background-color: #232323">
        <el-menu
          active-text-color="#86D6D6"
          background-color="#232323"
          text-color="#fff"
          class="el-menu-vertical-demo"
          default-active="1">
          <el-menu-item index="1" @click="changeShowInfo(1)">
            <el-icon><UserFilled /></el-icon>
            <span>个人信息</span>
          </el-menu-item>
          <el-menu-item index="2" @click="twoClickEvents2">
            <el-icon><HomeFilled /></el-icon>
            <span>商店管理</span>
          </el-menu-item>
          <el-sub-menu index="7">
            <template #title>
              <el-icon><Goods /></el-icon>
              订单状态
            </template>
            <el-menu-item index="5" @click="changeShowInfo(3)">待评价</el-menu-item>
            <el-menu-item index="6" @click="changeShowInfo(4)">全部订单</el-menu-item>
          </el-sub-menu>
        </el-menu>
      </el-aside>
      <el-main>
        <div class="person-info-show" v-if="showInfo == 1">
          <el-tabs v-model="activeName" class="demo-tabs">
            <el-tab-pane label="信息展示" name="first">
              <el-descriptions title="用户信息">
                <template #extra>
                  <el-button type="primary" @click="passwordChange = true">修改密码</el-button>
                  <el-button type="primary" @click="addMoneyShow = true">充值余额</el-button>
                </template>
                <el-descriptions-item label="用户名">{{ user.name }}</el-descriptions-item>
                <el-descriptions-item label="联系电话">{{ user.phone }}</el-descriptions-item>
                <el-descriptions-item label="住址">{{ user.address }}</el-descriptions-item>
                <el-descriptions-item label="性别">
                  <el-tag size="small">{{ user.gender == 1 ? '男' : '女' }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="邮箱">{{ user.email }}</el-descriptions-item>
                <el-descriptions-item label="生日">
                  {{ user.birthday }}
                </el-descriptions-item>
                <el-descriptions-item label="账户余额">￥{{ user.money }}</el-descriptions-item>
              </el-descriptions>
              <!-- 修改密码 -->
              <el-dialog v-model="passwordChange" title="修改密码" width="500" draggable>
                <el-form :model="passwordForm" label-width="auto" style="max-width: 600px">
                  <el-form-item label="旧密码">
                    <el-input
                      v-model="passwordForm.oldPassword"
                      placeholder="请输入修改前的密码"
                      show-password />
                  </el-form-item>
                  <el-form-item label="新密码">
                    <el-input
                      v-model="passwordForm.newPassword"
                      placeholder="请输入修改后的密码"
                      show-password />
                  </el-form-item>
                </el-form>
                <template #footer>
                  <div class="dialog-footer">
                    <el-button @click="cancel">取消</el-button>
                    <el-button type="primary" @click="passwordChangeEnter">确定</el-button>
                  </div>
                </template>
              </el-dialog>
              <!-- 充值余额 -->
              <el-dialog v-model="addMoneyShow" title="充值余额" width="250">
                <el-input-number
                  v-model="addMoney"
                  :min="1"
                  controls-position="right"
                  size="large" />
                <br />
                <span style="font-size: 12px; color: #777">充值后需等待并刷新页面</span>
                <template #footer>
                  <div class="dialog-footer">
                    <el-button @click="cancelAddMoney">取消</el-button>
                    <el-button type="primary" @click="addMoneySure">确定</el-button>
                  </div>
                </template>
              </el-dialog>
            </el-tab-pane>
            <el-tab-pane label="修改信息" name="second">
              <el-form
                label-position="top"
                label-width="auto"
                :model="userInfoForm"
                style="max-width: 600px"
                :rules="rules">
                <el-form-item label="用户名" prop="name">
                  <el-input v-model="userInfoForm.name" />
                </el-form-item>
                <el-form-item label="性别">
                  <div class="my-2 flex items-center text-sm">
                    <el-radio-group v-model="userInfoForm.gender" class="ml-4">
                      <el-radio value="1">男</el-radio>
                      <el-radio value="0">女</el-radio>
                    </el-radio-group>
                  </div>
                </el-form-item>
                <el-form-item label="用户邮箱" prop="email">
                  <el-input v-model="userInfoForm.email" />
                </el-form-item>
                <el-form-item label="出生日期">
                  <el-date-picker
                    v-model="userInfoForm.birthday"
                    type="datetime"
                    placeholder="出生日期" />
                </el-form-item>
                <el-form-item label="手机号" prop="phone">
                  <el-input v-model="userInfoForm.phone" />
                </el-form-item>
                <el-form-item label="居住地址" prop="address">
                  <el-input v-model="userInfoForm.address" />
                </el-form-item>
                <el-form-item>
                  <el-button type="primary" @click="changeUserInfo">修改信息</el-button>
                  <el-button @click="clearUserInfoForm">清空表单</el-button>
                </el-form-item>
              </el-form>
            </el-tab-pane>
          </el-tabs>
        </div>
        <div class="business-show" v-if="showInfo == 2">
          <el-button type="primary" style="margin-left: 1200px" @click="addBusinessButton">
            添加商店
          </el-button>
          <el-table v-if="business" :data="business" height="550" stripe style="width: 100%">
            <el-table-column prop="name" label="商店名称" width="180" />
            <el-table-column prop="type" label="商店分类" width="180" />
            <el-table-column prop="descInfo" label="商店描述" width="320" />
            <el-table-column prop="address" label="商店地址" width="320" />
            <el-table-column fixed="right" width="120">
              <template #default="scope">
                <el-button link type="primary" size="small" @click="manageInfo(scope.row)">
                  管理信息
                </el-button>
              </template>
            </el-table-column>
            <el-table-column fixed="right">
              <template #default="scope">
                <el-button link type="primary" size="small" @click="manageGoods(scope.row)">
                  管理商品
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-empty v-else description="没有数据" />
          <el-dialog
            v-model="manageBusiness"
            :title="addOrUpdateInfo ? '添加商店' : '修改商店信息'"
            width="500"
            draggable
            overflow>
            <el-form
              label-position="top"
              label-width="auto"
              :model="businessInfoForm"
              style="max-width: 600px"
              :rules="rulesBusiness"
              ref="businessForm">
              <el-form-item label="商店名" prop="name">
                <el-input v-model="businessInfoForm.name" placeholder="不超过20个字" />
              </el-form-item>
              <el-form-item label="商品分类" prop="type">
                <el-input
                  v-model="businessInfoForm.type"
                  placeholder="不超过15个字，分割符只能用、" />
              </el-form-item>
              <el-form-item label="商店描述" prop="descInfo">
                <el-input v-model="businessInfoForm.descInfo" placeholder="不超过50个字" />
              </el-form-item>
              <el-form-item label="商店地址" prop="address">
                <el-input v-model="businessInfoForm.address" placeholder="不超过30个字" />
              </el-form-item>
            </el-form>
            <template #footer>
              <div class="dialog-footer">
                <el-button @click="cancelAddBusiness">取消</el-button>
                <el-button v-if="addOrUpdateInfo" type="primary" @click="addBusiness">
                  增加
                </el-button>
                <el-button v-else type="primary" @click="updateBusinessInfo(updateId)">
                  更新
                </el-button>
              </div>
            </template>
          </el-dialog>
        </div>
        <div class="order-show" v-if="showInfo == 3">
          <el-scrollbar v-if="orders.length !== 0" max-height="700px">
            <OrderItem
              v-for="item in orders"
              :key="item.id"
              :item="item"
              @click="gotoDetail(item.id)"></OrderItem>
          </el-scrollbar>
          <el-empty v-if="orders.length == 0" description="暂无未评价订单" />
        </div>
        <div class="order-show" v-if="showInfo == 4">
          <el-scrollbar v-if="orders.length !== 0" max-height="700px">
            <OrderItem
              v-for="item in orders"
              :key="item.id"
              :item="item"
              @click="gotoDetail(item.id)"></OrderItem>
          </el-scrollbar>
          <el-empty v-if="orders.length == 0" description="暂无订单" />
        </div>
      </el-main>
    </el-container>
  </div>
</template>

<script setup>
import { UserFilled, Goods, HomeFilled } from '@element-plus/icons-vue'
import { ref, watch } from 'vue'
import { useUserStore } from '@/stores'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
import {
  changeUserInformation,
  getAllShop,
  updatePassword,
  addBusinessInfo,
  manageShop,
  updateBusiness,
  getOrders,
  addMoneys
} from '@/api/personInfo'
import OrderItem from '@/components/OrderItem.vue'

const router = useRouter()

const userStore = useUserStore()

const user = ref(userStore.getUserInfo())

const showInfo = ref(1)

const changeShowInfo = (num) => {
  showInfo.value = num
  isGetAllOrder()
}

//
// 个人信息
//
const activeName = ref('first')

const regex = {
  emailRegex:
    /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
  addressRegex: /^[^\r\n]{1,40}$/,
  phoneRegex: /^\+?[1-9]\d{1,14}(\(\d{1,3}\)|\s?\d{1,3})?[-.\s]?\d{1,14}$/
}

const rules = {
  name: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 1, max: 20, message: '用户名必须是1-20位字符', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    {
      pattern: regex.emailRegex,
      message: '请按照正确的格式输入邮箱',
      trigger: 'blur'
    }
  ],
  phone: [
    { required: true, message: '请输入正确的手机号', trigger: 'blur' },
    {
      pattern: regex.phoneRegex,
      message: '请按照正确的格式输入手机号',
      trigger: 'blur'
    }
  ],
  address: [
    { required: true, message: '请输入地址', trigger: 'blur' },
    {
      pattern: regex.addressRegex,
      message: '不能超过40个字符',
      trigger: 'blur'
    }
  ]
}

// 修改密码框
const passwordChange = ref(false)

// 密码表单
const passwordForm = ref({
  oldPassword: '',
  newPassword: ''
})

// 充值框
const addMoneyShow = ref(false)

// 充值数
const addMoney = ref()

// 取消充值
const cancelAddMoney = () => {
  addMoneyShow.value = false
  addMoney.value = ''
}

// 确认充值
const addMoneySure = async () => {
  if (addMoney.value > 1000000) {
    ElMessage.success('单次充值不能超过100万元')
    return
  }
  const res = (await addMoneys(addMoney.value, user.value.id)).data
  if (res.code == 504) {
    ElMessage.error(res.msg)
    return
  }
  user.value = userStore.getUserInfo()
  ElMessage.success('充值成功')
  addMoney.value = ''
  addMoneyShow.value = false
}

// 用户信息表单
const userInfoForm = ref({
  name: user.value.name,
  email: user.value.email,
  gender: user.value.gender,
  birthday: user.value.birthday,
  phone: user.value.phone,
  address: user.value.address
})

// 置空密码表单
const cancelPasswordForm = () => {
  passwordForm.value = {
    oldPassword: '',
    newPassword: ''
  }
}

// 修改密码
const passwordChangeEnter = async () => {
  const oldPassword = user.value.password
  if (passwordForm.value.oldPassword !== oldPassword) {
    ElMessage.error('修改前的密码与原密码不一致')
    return
  }
  const res = (await updatePassword(user.value, passwordForm.value)).data
  if (res.code == 504) {
    ElMessage.error(res.msg)
  } else {
    // 更新状态管理仓的信息
    userStore.updatePassword(passwordForm.value.newPassword)
    user.value = userStore.getUserInfo()
    ElMessage.success('修改密码成功')
  }
  cancelPasswordForm()
  passwordChange.value = false
}

// 取消修改密码
const cancel = () => {
  cancelPasswordForm()
  passwordChange.value = false
}

// 修改用户信息
const changeUserInfo = async () => {
  const moneyTemp = user.value.money
  // 转化成时间对象，否则后端的Date类型无法接受
  userInfoForm.value.birthday = new Date(userInfoForm.value.birthday)
  const res = (await changeUserInformation(userInfoForm.value, user.value)).data
  if (res.code == 504) {
    ElMessage.error(res.msg)
    return
  } else {
    user.value = {
      ...userInfoForm.value,
      id: user.value.id,
      username: user.value.username,
      password: user.value.password
    }
    const date = new Date(userInfoForm.value.birthday)
    user.value.birthday = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
    user.value.money = moneyTemp
    ElMessage.success('修改用户信息成功')
  }
}

// 清空表单
const clearUserInfoForm = () => {
  userInfoForm.value = {
    name: '',
    email: '',
    gender: '',
    birthday: '',
    phone: '',
    address: ''
  }
  ElMessage.success('已成功清除表单')
}

//
// 商店管理
//
const twoClickEvents2 = () => {
  changeShowInfo(2)
  getAllBusiness()
}

const businessForm = ref()

const manageBusiness = ref(false)

const business = ref([])

const regexBusiness = {
  typeRegex:
    /^(?:([\u4e00-\u9fa5\w]{1,14})(?:、([\u4e00-\u9fa5\w]{1,13}))*|([\u4e00-\u9fa5\w]{1,15}))$/,
  nameRegex: /^[^\r\n]{1,20}$/,
  descRegex: /^[^\r\n]{1,50}$/,
  addressRegex: /^[^\r\n]{1,30}$/
}

const rulesBusiness = {
  name: [
    { required: true, message: '请输入商店名', trigger: 'blur' },
    {
      pattern: regexBusiness.typeRegex,
      message: '不能超过20个字符',
      trigger: 'blur'
    }
  ],
  type: [
    { required: true, message: '请输入分类', trigger: 'blur' },
    {
      pattern: regexBusiness.typeRegex,
      message: '不能超过15个字符，且分割符只能用、',
      trigger: 'blur'
    }
  ],
  descInfo: [
    { required: true, message: '请输入商品描述', trigger: 'blur' },
    {
      pattern: regexBusiness.descRegex,
      message: '不能超过50个字符',
      trigger: 'blur'
    }
  ],
  address: [
    { required: true, message: '请输入商店地址', trigger: 'blur' },
    {
      pattern: regexBusiness.addressRegex,
      message: '不能超过30个字符',
      trigger: 'blur'
    }
  ]
}

const businessInfoForm = ref({
  name: '',
  type: '',
  descInfo: '',
  address: ''
})

// 获取商店
const getAllBusiness = async () => {
  const res = (await getAllShop(user.value)).data
  if (res.code == 505) {
    ElMessage.error(res.msg)
    return
  }
  business.value = res.data
}

// 置空表单
const clearBusinessInfoForm = () => {
  businessInfoForm.value = {
    name: '',
    type: '',
    descInfo: '',
    address: ''
  }
}

// 取消添加
const cancelAddBusiness = () => {
  manageBusiness.value = false
  clearBusinessInfoForm()
}

const addOrUpdateInfo = ref(true) // 默认为增加

const addBusinessButton = () => {
  addOrUpdateInfo.value = manageBusiness.value = true
}

// 增加商店
const addBusiness = async () => {
  businessForm.value.validate()
  const res = (await addBusinessInfo(user.value, businessInfoForm.value)).data
  if (res.code == 504) {
    ElMessage.error(res.msg)
    return
  }
  clearBusinessInfoForm()
  getAllBusiness()
  ElMessage.success('添加商店成功')
  manageBusiness.value = false
}

const updateId = ref()

// 管理商店信息
const manageInfo = async (value) => {
  updateId.value = value.id
  addOrUpdateInfo.value = false
  const res = (await manageShop(value, user.value)).data
  manageBusiness.value = true
  businessInfoForm.value = res.data
}

// 更新商店信息
const updateBusinessInfo = async () => {
  businessForm.value.validate()
  const res = (await updateBusiness(user.value, updateId, businessInfoForm.value)).data
  if (res.code == 504) {
    ElMessage.error(res.msg)
    return
  }
  ElMessage.success('更新信息成功')
  clearBusinessInfoForm()
  getAllBusiness()
  manageBusiness.value = false
}

// 跳转到管理商品界面
const manageGoods = (value) => {
  router.replace({
    name: 'Goods',
    params: {
      id: value.id // 商店id
    }
  })
}

//
// 订单信息
//
const orders = ref([])

// 获取订单
const getOrder = async (flag) => {
  const res = (await getOrders(user.value.id, flag)).data
  if (res.code == 505) {
    ElMessage.error(res.msg)
    return
  }
  orders.value = res.data
  console.log(orders.value)
}

const isGetAllOrder = () => {
  if (showInfo.value == 3) {
    // 待评价
    getOrder(0)
  } else {
    // 全部订单
    getOrder(1)
  }
}

// 跳到详细页
const gotoDetail = (id) => {
  router.push({
    name: 'Detail',
    params: {
      id
    }
  })
}
</script>

<style scoped>
.personInformation {
  width: 100%;
  height: 700px;
  background-color: white;
}

.person-info-show,
.business-show,
.order-show {
  height: 660px;
}
</style>
